package com.ruoyi.web.controller.oss;

import java.io.ByteArrayOutputStream;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.oss.cloud.CloudStorageConfig;
import com.ruoyi.oss.cloud.OSSFactory;
import com.ruoyi.oss.domain.OssFile;
import com.ruoyi.oss.service.IOssFileService;
import com.ruoyi.oss.service.IOssService;
import com.ruoyi.system.service.ISysUserService;
import cn.hutool.core.img.ImgUtil;

/**
 * 文件上传
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/oss/oss")
public class OssController extends BaseController {
	
	private static final Logger log = LoggerFactory.getLogger(OssController.class);
	
	@Autowired
	private IOssService ossService;
	
	@Autowired
    private ISysUserService sysUserService;
	
	@Autowired
	private IOssFileService ossFileService;
	
	/**
	 * 云存储配置信息
	 * @return
	 */
	@GetMapping("info")
    public R<CloudStorageConfig> info(){
        CloudStorageConfig  config = ossService.getValueObject(CloudStorageConfig.class);
        return R.ok(config);
    }
	
	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	@Anonymous
	@PostMapping("upload")
	public R<String> upload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return R.fail();
		}

		try {
			//上传文件
			String extension = FilenameUtils.getExtension(file.getOriginalFilename());
			
			// 压缩图片到200K
			float scale = scale200K(file.getSize());
			ByteArrayOutputStream targetImageStream = new ByteArrayOutputStream(file.getBytes().length);
			ImgUtil.scale(file.getInputStream(), targetImageStream, scale);
			String url = OSSFactory.build().uploadSuffix(targetImageStream.toByteArray(), extension);
			// 正常用户需要校验合法性
			String checkMsg = OSSFactory.build().check(url);
			if(StringUtils.isNotBlank(checkMsg)){
				throw new ServiceException(checkMsg);
			}
			//保存文件信息
			OssFile ossFile = new OssFile();
			ossFile.setName(FileUtils.getName(url));
			ossFile.setOriginalName(file.getOriginalFilename());
			ossFile.setUrl(url);
			ossFileService.saveOrUpdate(ossFile);
			return R.ok(url);
		} catch (Exception e) {
			log.error("上传文件失败", e);
            return R.fail(e.getMessage());
		}
	}
	
	private static float scale200K(long srcSize) {
        float scale = 0f;
        if (srcSize < 200 * 1000) {
            scale = 1.00f;
        } else if (srcSize < 500 * 1000) {
            scale = 0.57f;
        } else if (srcSize < 700 * 1000) {
            scale = 0.47f;
        } else if (srcSize < 1 * 1000 * 1000) {
            scale = 0.37f;
        } else if (srcSize < 2 * 1000 * 1000) {
            scale = 0.25f;
        } else if (srcSize < 4 * 1000 * 1000) {
            scale = 0.17f;
        } else if (srcSize < 5 * 1000 * 1000) {
            scale = 0.13f;
        } else if (srcSize < 10 * 1000 * 1000) {
            scale = 0.10f;
        } else {
            scale = 0.01f;
        }
        return scale;
    }
	
    @GetMapping("/list")
    public TableDataInfo list(OssFile ossFile)
    {
        startPage();
        List<OssFile> list = ossFileService.selectImMessageList(ossFile);
        return getDataTable(list);
    }
    
    @PostMapping("/remove")
    public AjaxResult remove(String ids)
    {
        return toAjax(ossFileService.deleteByIds(ids));
    }
	
	@PostMapping("saveConfig")
	public R<Boolean> saveConfig(@RequestBody CloudStorageConfig config){
		ossService.saveConfig(config);
		return R.ok();
	}

}
